<template>
    <el-dialog v-model="visible" :show-close="false" width="500">
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">{{ titleInfo }}:</h4>
                <el-button type="danger" @click="visible = false">
                    <el-icon class="el-icon--left">
                        <CircleCloseFilled />
                    </el-icon>
                    Close
                </el-button>
            </div>
        </template>
        <el-form :ref="($event) => setRef($event)" :model="ddata" label-width="auto" class="q-form flex wrap"
            :class="['q-form-' + name, 'q-form-' + name.slice(-4), `flex-${flex}-start`, refName]">
            <div v-for="(i, n) in form.filter((i) => i)" :key="n" :class="[i.class, i.prop]"
                :style="i.hidden && { display: 'none', margin: 0 }">
                <slot :name="i.slot" :pItem="i">
                    <div class="flex has-els" :class="[i.prop, i.class]">
                        <el-form-item v-for="(el, elIndex) in i.els" :key="elIndex"
                            :class="[el.class, el.prop, el.prop + '_' + el.el]"
                            :label="el.label && !['h2', 'h3'].includes(el.el) ? el.label : ''" :prop="el.prop"
                            :rules="getRules(el)" :style="el.hidden && { display: 'none', margin: 0 }">
                            <slot :name="el.slot" :sItem="el" v-if="!el.hidden">
                                <elsContainer :el="el" :isView="isView" :data="ddata" @change="onChange" @resetTree="onResetTree"/>
                            </slot>
                        </el-form-item>
                    </div>
                </slot>
                <slot name="item-handle" :pItem="i"></slot>
            </div>
            <div class="handle">
                <el-button v-if="showCancel" plain @click="visible = false">{{ cancelText }}</el-button>
                <el-button v-if="showSure" plain type="primary" 
                    @click="onCheck(refName == 'flowDigFormRef' ? flowDigFormRef : FormRef, () => $emit('confirm'))">
                    {{ sureText }}
                </el-button>
            </div>
        </el-form>
    </el-dialog>
</template>


<script setup>
import { defineProps, ref, reactive, defineEmits, watch, provide } from "vue";
import elsContainer from "../element-ui.vue";
import { CircleCloseFilled } from '@element-plus/icons-vue';
const emits = defineEmits(["confirm", "change", "check", 'resetTree']);
const props = defineProps({
    sureText: {
        type: String,
        default: "确 定"
    },
    cancelText: {
        type: String,
        default: "取 消"
    },
    showSure: {
        type: Boolean,
        default: true
    },
    showCancel: {
        type: Boolean,
        default: true
    },
    showClear: {
        type: Boolean,
        default: false
    },
    refName: {
        type: String,
        default: "FormRef"
    },
    ddata: {
        type: Object,
        default: () => {}
    },
    form: {
        type: Array,
        default: () => []
    },
    name: {
        type: String,
        default: ""
    },
    flex: {
        type: String,
        default: "col"
    },
    isView: {
        type: Boolean,
        default: false
    },
});

const visible = ref(false);
let titleInfo = ref('');
const showDialog = (show, title) => {
    if(show) {
        titleInfo.value = title;
    }
    visible.value = show;
    
}

const treeRef = ref();
const cascaderRef = ref();

const FormRef = ref();
const flowDigFormRef = ref();
const setRef = e => {
    let { refName } = props;
    switch (refName) {
        case "FormRef":
            FormRef.value = e;
            break;
        case "flowDigFormRef":
            flowDigFormRef.value = e;
            break;
    }
};

const getRules = e => {
    let { el, hidden, els, required, label, place } = e;
    let message = `请${el && el.includes("input") ? "输入" : "选择"}${label || place || "内容"}`;
    let nowrequired;
    if (required == undefined) {
        nowrequired =
            hidden == undefined
                ? ["true", "1"].includes(
                    `${required == undefined ? !(el == "p" || hidden || els) : required
                    }`
                )
                : !hidden;
    } else {
        nowrequired = required;
    }
    return [
        {
            required: nowrequired,
            message,
            trigger: ["blur", "change"]
        }
    ];
};

const onCheck = (formRef, fn) => {
    if (!formRef) return;
    formRef.validate((valid) => {
        if (valid) {
            emits("confirm", props.ddata, titleInfo.value);
            visible.value = false;
            // fn && fn();
        } else {
            console.error("error submit!");
            return false;
        }
    });
};

const onChange = (type, checked, event) => {
    switch (type) {
        case 'tree':
            if(checked && event) {
                props.ddata.rules.push(event);
            }else {
                const index = props.ddata.rules.indexOf(event);
                if(index > -1) {
                    props.ddata.rules.splice(index, 1);
                }
            }
            break;
        case 'cascader':
            props.ddata.pid = event;
            break;
    }
};

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields();
}

const resetTree = (treeEl) => {
    if (!treeEl) return
    treeEl.setCheckedKeys([]);
}

const onResetTree = (type, event) => {
    switch (type) {
        case 'tree':
            treeRef.value = event;
            break;
        case 'cascader':
            cascaderRef.value = event;
            break;
    }
   
}

watch(visible, (newVal) => {
    if(!newVal) {
        if(treeRef.value) resetTree(treeRef.value);
        resetForm(FormRef.value);
    }
})

defineExpose({ showDialog })
</script>

<style scoped lang="scss">
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}

.condition {
    min-width: 100%;
}

.tip {
    p {
        color: #f00;
        font-size: 10px;
        transform: scale(0.9);
        position: absolute;
        margin-left: 68px !important;
        margin-top: 5px;
    }
}

.flex-col-start {
    >div {
        width: 100%;
    }
}

.el-form {
    padding-bottom: 10px;

    >div {
        ::v-deep .el-form-item {
            width: 100%;

            .el-form-item__content {
                >div {
                    >p {
                        margin-left: 20px;
                    }
                }
            }
        }
    }

    .handle {
        width: 100% !important;
    }

    >div {
        flex: 0 0 100%;
        align-items: center;

        >h4 {
            margin-bottom: 10px;
            font-size: 15px;

            >i {
                color: #f00;
                margin-right: 4px;
            }
        }

        >div {
            .el-form-item {
                margin-bottom: 15px;

                ::v-deep .el-form-item__error {
                    // top: 105%;
                    left: 10px;
                }
            }
        }
    }

    >.handle {
        flex: 0 0 100% !important;
        text-align: right;
    }
}
</style>